package lt.marsrutai.mobile.android.dao.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Methods to work with various date representations in the dao layer
 * 
 * @author Martynas
 * 
 */
public class DateUtils {

    /**
     * 
     * @param datetime
     *            Datetime in output format. For example: 2012-10-27T04:07
     * 
     * @return
     */
    private static Calendar getCalendarFromInputDateTime(String datetime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.US);

        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(format.parse(datetime));
        }
        catch (ParseException e) {
            e.printStackTrace();
        }

        return calendar;
    }
    
    public static int getWeekdayFromInputDatetime(String datetime) {
        return getCalendarFromInputDateTime(datetime).get(Calendar.DAY_OF_WEEK) - 1;
    }
    
    public static Date getDateFromInputDateTime(String dateTime) {
        return getCalendarFromInputDateTime(dateTime).getTime();
    }

    /**
     * 
     * @param datetime
     *            Datetime in input format. For example:
     *            /Date(1298707680000+0200)/
     * 
     * @return
     */
    public static Date getDateFromOutputDatetime(String datetime) {
        Long milliseconds = Long.parseLong(datetime.substring(6, datetime.indexOf("+")));
        return new Date(milliseconds);
    }
}
